package com.example.smartcity.ui.home;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;



import androidx.annotation.NonNull;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;


import com.bumptech.glide.Glide;

import com.example.smartcity.R;
import com.example.smartcity.ui.Adapter.NewsViewPagerAdapter;
import com.example.smartcity.ui.Adapter.RecycleViewAdapter;
import com.example.smartcity.ui.Adapter.TopicAdapter;
import com.example.smartcity.ui.Bean.FirstPageBannerBean;
import com.example.smartcity.ui.Bean.NewsBean;
import com.example.smartcity.ui.Bean.NewsKind;
import com.example.smartcity.ui.Bean.TopicBean;
import com.example.smartcity.ui.Bean.TopicMessageBean;
import com.example.smartcity.ui.Bean.topicFunctionBean;
import com.example.smartcity.ui.Tools.File;
import com.example.smartcity.ui.dashboard.LifeGit;
import com.example.smartcity.ui.dashboard.ViolationInquiry;
import com.example.smartcity.ui.Tools.OkHttpUtils;

import com.example.smartcity.ui.dashboard.CitySubway;
import com.example.smartcity.ui.dashboard.OrderHospital;
import com.example.smartcity.ui.dashboard.SmartBar;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.google.gson.Gson;



import com.youth.banner.Banner;
import com.youth.banner.adapter.BannerImageAdapter;
import com.youth.banner.holder.BannerImageHolder;
import com.youth.banner.indicator.CircleIndicator;


import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

import com.example.smartcity.ui.home.Fragment.*;

public class HomeFragment extends Fragment {


    private TabLayout TL_NewsKind;
    private ViewPager2 VP_NewsMessage;
    private String TAG = "TAG";
    ArrayList<topicFunctionBean> listBeans = new ArrayList<>();
    String titles[] = {"城市地铁","智慧巴士","门诊预约","生活缴费","违章查询"};
    int icons[] = {R.drawable.citysubway, R.drawable.smartbar, R.drawable.hospital, R.drawable.lifegit, R.drawable.findcar};
    public Banner banner;
    private GridView gridView;
    private RecyclerView recycleView;
    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_home, container, false);
        banner = root.findViewById(R.id.banner);
        gridView = root.findViewById(R.id.gridView);
        recycleView = root.findViewById(R.id.CSrecycleView);
        TL_NewsKind = root.findViewById(R.id.TL_NewsKind);
        VP_NewsMessage = root.findViewById(R.id.NewsViewPager);
        initRecycleView();
        initBanner();
        initGridView();
        initNewsKinds();
        return root;
    }

    //Banner轮播图
    public void initBanner(){
        String newUrl = OkHttpUtils.getBaseUrl(HomeFragment.this.getContext()) + "/userinfo/rotation/list?pageNum=1&pageSize=10&type=45";
        OkHttpUtils.getCall(newUrl).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "onFailure: "+e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String json = response.body().string();
                ArrayList<String> photos = new ArrayList<>();
                ArrayList<FirstPageBannerBean.RowsBean> rowsBeanList = new ArrayList<>();
                FirstPageBannerBean bean = new Gson().fromJson(json,FirstPageBannerBean.class);
                List<FirstPageBannerBean.RowsBean> rowsBeans = bean.getRows();
                if (rowsBeans!=null){
                    rowsBeanList.addAll(rowsBeans);
                }
                for (int i = 0; i < rowsBeanList.size(); i++) {
                    photos.add(OkHttpUtils.getBaseUrl(HomeFragment.this.getContext()) + rowsBeanList.get(i).getImgUrl());
                }
                banner.post(new Runnable() {
                    @Override
                    public void run() {
                        banner.setAdapter(new BannerImageAdapter<FirstPageBannerBean.RowsBean>(rowsBeans) {
                            @Override
                            public void onBindView(BannerImageHolder bannerImageHolder, FirstPageBannerBean.RowsBean rowsBean, int i, int i1) {
                                String path = OkHttpUtils.getBaseUrl(getContext())+rowsBean.getImgUrl();
                                Glide.with(getContext()).load(path)
                                        .into(bannerImageHolder.imageView);
                            }
                        }).setIndicator(new CircleIndicator(HomeFragment.this.getContext()))
                                .start();
                    }
                });
            }
        });
    }

    //推荐服务
    public void initRecycleView(){
        for (int i = 0; i < 5; i++) {
            topicFunctionBean bean = new topicFunctionBean(titles[i],icons[i]);
            listBeans.add(bean);
        }
        LinearLayoutManager layoutManager = new LinearLayoutManager(HomeFragment.this.getContext());
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recycleView.setLayoutManager(layoutManager);
        RecycleViewAdapter adapter = new RecycleViewAdapter(listBeans,R.layout.topicefunctionitem);
        recycleView.setAdapter(adapter);
        adapter.setOnItemClickListener(new RecycleViewAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void OnItemClickLister(int position) {
                //推荐服务跳转
                Intent intent;
                switch (position){
                    case 0:
                        //停车场
//                        startActivity(new Intent(HomeFragment.this.getContext(), stopCar.class));
                        //城市地铁
                        startActivity(new Intent(HomeFragment.this.getContext(), CitySubway.class));
                        break;
                    case 1:
                         intent = new Intent(HomeFragment.this.getContext(), SmartBar.class);
                         startActivity(intent);
                        break;
                    case 2:
                        startActivity(new Intent(HomeFragment.this.getContext(), OrderHospital.class));
                        break;
                    case 3:
                        startActivity(new Intent(HomeFragment.this.getContext(), LifeGit.class));
                        break;
                    case 4:
                        startActivity(new Intent(HomeFragment.this.getContext(), ViolationInquiry.class));
                        break;
                }
            }
        });
    }
    //专题
    public void initGridView(){
        Intent intent;
        ArrayList<TopicBean> dataList = new ArrayList<>();
        ArrayList<Integer> idList = new ArrayList<>();
        ArrayList<String> titleList = new ArrayList<>();
        ArrayList<String> contentList = new ArrayList<>();
        ArrayList<String> imgUrlList = new ArrayList<>();
        String newUrl = OkHttpUtils.getBaseUrl(HomeFragment.this.getContext()) + "/press/press/list?pageNum=1&pageSize=10&pressCategory=48";
        OkHttpUtils.getCall(newUrl,new File(HomeFragment.this.getContext()).readFile("Token")).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "onFailure: "+e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String json = response.body().string();
                ArrayList<TopicMessageBean.RowsBean> tempList = new ArrayList<>();
                TopicMessageBean bean = new Gson().fromJson(json,TopicMessageBean.class);
                List<TopicMessageBean.RowsBean> list = bean.getRows();
                if (list!=null){
                    tempList.addAll(list);
                }
                for (int i = 0; i < tempList.size(); i++) {
                    idList.add(tempList.get(i).getId());
                    titleList.add(tempList.get(i).getTitle());
                    contentList.add(tempList.get(i).getContent());
                    imgUrlList.add(OkHttpUtils.getBaseUrl(getContext())+tempList.get(i).getImgUrl());
                }
                int totals = bean.getTotal();
                int code = bean.getCode();
                if (code==200){
                    gridView.post(new Runnable() {
                        @Override
                        public void run() {
                            for (int i = 0; i < totals; i++) {
                                TopicBean bean1 = new TopicBean(imgUrlList.get(i),contentList.get(i));
                                dataList.add(bean1);
                            }
                            gridView.setAdapter(new TopicAdapter(dataList,R.layout.zhuantiitemlayout));
                        }
                    });
                }
            gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Intent intent1 = new Intent(HomeFragment.this.getContext(),News.class);
                    intent1.putExtra("title",titleList.get(position));
                    intent1.putExtra("imgUrl",imgUrlList.get(position));
                    intent1.putExtra("Content",contentList.get(position));
                    startActivity(intent1);
                }
            });
            }
        });
    }

    //新闻分类
    public void initNewsKinds(){
        ArrayList<Integer> dictCodeList = new ArrayList<>();
        String NewsKindUrl = OkHttpUtils.getBaseUrl(HomeFragment.this.getContext()) + "/system/dict/data/type/press_category";
        OkHttpUtils.getCall(NewsKindUrl).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "onFailure: ");e.getMessage();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                ArrayList<String> NewsKindList = new ArrayList<>();
                ArrayList<NewsKind.DataBean> tempList = new ArrayList<>();
                NewsKind bean = new Gson().fromJson(response.body().string(),NewsKind.class);
                int code = bean.getCode();
                if (code==200){
                    List<NewsKind.DataBean> dataBeans = bean.getData();
                    if (dataBeans!=null){
                        tempList.addAll(dataBeans);
                    }
                        TL_NewsKind.post(new Runnable() {
                            @Override
                            public void run() {
                                for (int i = 0; i < tempList.size(); i++) {
                                    NewsKindList.add(tempList.get(i).getDictLabel());
                                    dictCodeList.add(tempList.get(i).getDictCode());
                                }
                                try {
                                    initNewsMessage(dictCodeList,NewsKindList);
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                }
            }
        });
    }

    //新闻内容
    public void initNewsMessage(ArrayList<Integer> dictCodeList,ArrayList<String> NewsKindList) throws IOException {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    List<Fragment> fragments = new ArrayList<>();
                    //每个Fragment中的信息组
                    ArrayList<List<NewsBean.RowsBean>> list = new ArrayList<>();
                    for (int i = 0; i < dictCodeList.size(); i++) {
                        String NewsUrl = OkHttpUtils.getBaseUrl(HomeFragment.this.getContext())+"/press/press/list?pageNum=1&pageSize=10&pressCategory="+dictCodeList.get(i);
                        String json = null;
                        try {
                            json = OkHttpUtils.getCall(NewsUrl).execute().body().string();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        NewsBean bean = new Gson().fromJson(json,NewsBean.class);
                        List<NewsBean.RowsBean> tempList = bean.getRows();
                        if (bean.getCode()==200){
                            if (tempList!=null){
                                list.add(tempList);
                            }
                        }
                    }
                    //初始话Fragment
                    for (int i = 0; i < 6; i++) {
                        fragments.add(f1.newInstance(list.get(i)));
                    }
                    //配置适配器
                    NewsViewPagerAdapter adapter = new NewsViewPagerAdapter(getChildFragmentManager(),getLifecycle(),fragments);
                    VP_NewsMessage.post(new Runnable() {
                        @Override
                        public void run() {
                            VP_NewsMessage.setAdapter(adapter);
                            new TabLayoutMediator(TL_NewsKind,VP_NewsMessage, new TabLayoutMediator.TabConfigurationStrategy() {
                                @Override
                                public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
                                    //设置TabLayout的标签
                                    tab.setText(NewsKindList.get(position));
                                }
                            }).attach();
                        }
                    });
                }
            }).start();


    }


}